package yz.cp.back.auth.security.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import yz.cp.back.auth.security.ImAuthenticationFilter;
import yz.cp.back.common.integration.IntegrationAuthentication;
import yz.cp.back.common.integration.IntegrationAuthenticationContext;
import yz.cp.back.common.integration.authenticator.IntegrationAuthenticator;
import yz.cp.back.common.res.ApiResult;
import yz.cp.back.common.utils.ServletUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

@Slf4j
public class AuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    public AuthenticationSuccessHandler() {
    }

    public AuthenticationSuccessHandler(String defaultTargetUrl) {
        super(defaultTargetUrl);
    }

    private static final ApiResult LOGIN_SUCCESS_RESULT = ApiResult.Custom().success();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth) throws IOException, ServletException {
        if (!complete(request, response, auth)) {
            if (ServletUtils.isAjaxRequest(request)) {
                ServletUtils.renderResult(response, LOGIN_SUCCESS_RESULT);
            } else {
                super.onAuthenticationSuccess(request, response, auth);
            }
        }
    }

    /**
     * 进行预处理
     *
     * @param auth
     */
    private boolean complete(HttpServletRequest request, HttpServletResponse response, Authentication auth) {
        IntegrationAuthentication integrationAuthentication = IntegrationAuthenticationContext.get();
        if (integrationAuthentication == null) {
            integrationAuthentication = new IntegrationAuthentication();
            if (!(auth instanceof UsernamePasswordAuthenticationToken)) {
                integrationAuthentication.setAuthType("none");
            }
        }
        Collection<IntegrationAuthenticator> authenticators = ImAuthenticationFilter.authenticators;
        if(authenticators!=null){
            for (IntegrationAuthenticator authenticator : authenticators) {
                if (authenticator.support(integrationAuthentication)) {
                    return authenticator.complete(request, response, auth, null);
                }
            }
        }
        return false;
    }
}
